import Vue from 'vue'
import { Loading } from 'element-ui';

import { getButtons } from "@/api/login";//按钮权限

/**
 * 按钮权限
 * By：苏恩泽
 */
var button_list=null;
var url = null;
//初始化
//var loading = null;
var loadingList = [];

export function permConfig(path){//



		if(path.indexOf('/')==0) path=path.substring(1,path.length);
		url=path;
				getButtons(url).then(response => {
					var rlist = response.data;
					button_list=[];
						for (var i = 0; i < rlist.length; i++) {
								button_list.push(rlist[i].name)
						}
				});

}


//获取节点
export const bntPerm = Vue.directive('bntPerm', {
	bind: function (el, binding, vnode) {
		//获取父节点
		//隐藏父节点
		el.style.display ="none";
		//if(!loading){
		var	loading = Loading.service(
					{
					  target:el.parentNode,
					  lock: true,
					  text: '按钮加载中。。。',
					  spinner: 'el-icon-loading',
					  background: 'rgba(255, 255, 255, 0.8)'
					}
			);
			loadingList.push(loading)
		//}


		//console.log(el.parentNode);
		var code=binding.value;
		setTimeout(() => {
				remove_el(el,code);
		}, 500);
		//显示父节点
	},
	unbind: function (el, binding, vnode) {
			button_list = null;
			//showEl(el);
	},
});
//显示父节点
function showEl(el){
	//setTimeout(() => {

		for (var i = 0; i < loadingList.length; i++) {
			loadingList[i].close();
		}
		el.style.display ="";
	//}, 500);

}

//如果不包含，移除节点
function remove_el(el,code){
	if(button_list==null){
		getButtons(url).then(response => {
		var rlist = response.data;
		button_list=[];
			for (var i = 0; i < rlist.length; i++) {
					button_list.push(rlist[i].name)
			}
			if(button_list.indexOf(code)==-1){
				el.parentNode.removeChild(el);
			}
			//重新显示按钮
			showEl(el);
		});
	}else{
		if(button_list.indexOf(code)==-1){
			el.parentNode.removeChild(el);
		}
		//重新显示按钮
		showEl(el);
	}



}


//export {bntPerm}

/***
用法:
引入：
import {bntPerm}  from "@/utils/btnPermissions.js";//权限验证工具
data添加：
moduleName:'company_index',//模块名称，处理权限用的
按钮添加
v-bntPerm="{moduleName:moduleName,code:'AAA'}"
***/
